package db

import (
	"time"
	"yunpan/cache/log"
	mydb "yunpan/db/mysql"
)

type UserFile struct {
	UserName string
	FileHash string
	FileName string
	FileSize int64
	UploadAt string
	LastUpdated string
}

func OnUserFileUploadFinished(username, filehash, filename string, filesize int64) bool {
	stmt, err := mydb.DBConn().Prepare("insert ignore into tbl_user_file (`user_name`, " +
		" `file_sha1`, `file_name`, `file_size`, `upload_at`) values (?,?,?,?,?)")

	if err != nil {
		log.Ob().Warn("userfile prepare"+err.Error())
		return false
	}

	defer stmt.Close()

	_, err = stmt.Exec(username, filehash,filename, filesize, time.Now())
	if err != nil {
		log.Ob().Warn("insert into user_file err:"+err.Error())
		return false
	}
	return true
}

func QueryUserFileMetas(username string, limit int) ([]UserFile, error) {
	stmt, err := mydb.DBConn().Prepare("select file_sha1, file_name, file_size, upload_at, " +
		" last_update from tbl_user_file where user_name=? limit ?")
	if err != nil {
		log.Ob().Warn("query userfile prepare err:"+err.Error())
		return nil, err
	}
	defer stmt.Close()
	rows, err := stmt.Query(username, limit)
	if err != nil {
		log.Ob().Warn("query err:"+err.Error())
		return nil, err
	}
	var userFiles []UserFile
	for rows.Next() {
		var userFile UserFile
		err := rows.Scan(&userFile.FileHash,&userFile.FileName, &userFile.FileSize, &userFile.UploadAt,&userFile.LastUpdated)
		if err != nil {
			log.Ob().Warn(err.Error())
			break
		}
		userFiles = append(userFiles, userFile)
	}

	return userFiles, nil
}